package com.zmytest.aop;

import com.zmytest.annotation.Permission;
import com.zmytest.dto.LoginResponseDto;
import com.zmytest.dto.ResponseDto;
import com.zmytest.model.LoginRecord;
import com.zmytest.repository.LoginRecordRepository;
import com.zmytest.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * Created on 2019/1/3.
 *
 * @author zhangmingyu
 */
@Aspect
@Component
@Slf4j
public class PermissionAspect {

    @Autowired
    private SessionService sessionService;
    @Autowired
    private LoginRecordRepository loginRecordRepository;

    @Pointcut(value = "@annotation(com.zmytest.annotation.Permission)")
    public void pointCut(){}

    @Around(value = "pointCut() && @annotation(permission)")
    public Object test(ProceedingJoinPoint pjp, Permission permission) throws Throwable {
        LoginResponseDto loginInfo = (LoginResponseDto) sessionService.get("LOGIN_INFO");
        if (ObjectUtils.isEmpty(loginInfo)) {
            return ResponseDto.fail("login token not exist");
        }
        LoginRecord record = loginInfo.getLogin();
        if (record.getExpireTime().isBefore(LocalDateTime.now())) {
            record.setEnable(false);
            loginRecordRepository.save(record);
            return ResponseDto.fail("login expired");
        }
        if (!loginInfo.getAccount().hasPermission(permission.value())) {
            return ResponseDto.fail("account has no Permission");
        }
        return pjp.proceed();
    }

}
